package com.dong.mjblog.controller;

import com.dong.mjblog.dto.CommentListDTO;
import com.dong.mjblog.entity.QuestionEntity;
import com.dong.mjblog.entity.UserEntity;
import com.dong.mjblog.enums.CommentTypeEnum;
import com.dong.mjblog.exception.CustomizeErrorCode;
import com.dong.mjblog.exception.CustomizeException;
import com.dong.mjblog.service.impl.CommentImpl;
import com.dong.mjblog.service.impl.QuestionImpl;
import com.dong.mjblog.service.impl.UserImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

/**
 * @Author:dxf
 * @Date:2020/10/28-10-28 20:53
 */
@Controller
public class QuestionController {

    @Autowired
    private QuestionImpl question;

    @Autowired
    private UserImpl user;

    @Autowired
    private CommentImpl commentImpl;

    @GetMapping("question/{id}")
    public String question(@PathVariable(name = "id") Long id,
                           Model model) {
        QuestionEntity questionEntity = question.getById(id);
        if (questionEntity == null) {
            throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FOUND);
        }

        List<QuestionEntity> relatedQeustions = question.selectRelated(questionEntity);
        UserEntity userEntity = user.getById(questionEntity.getCreator());
        questionEntity.setUser(userEntity);

        List<CommentListDTO> comments = commentImpl.listByTargetId(id, CommentTypeEnum.QUESTION);

        //每请求一次页面，增加一次浏览量
        question.incView(id);

        model.addAttribute("question", questionEntity);
        model.addAttribute("comments", comments);
        model.addAttribute("relatedQuestions", relatedQeustions);
        return "question";
    }
}
